package com.example.demo.file.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.CommonUtil;
import com.example.demo.common.ExportExcel;
import com.example.demo.common.GenerateExcelUtil;
import com.example.demo.file.pojo.FileUpload;
import com.example.demo.file.service.FileService;
import com.example.demo.laws.service.impl.AeolLawsServiceImpl;

/**
 * 
 * <p>
 * 功能描述： 文件控制层
 * </p>
 * 
 * @author lixh
 * @date 2019年2月21日 上午9:42:48
 * @company chinobot
 * @version 1.0
 */
@RestController
public class FileController {
	@Autowired
	private FileService fileservice;

	private String UPLOAD_DIR = "F:\\upload";

	@Autowired
	AeolLawsServiceImpl aeollawsserviceimpl;

	/**
	 * 
	 * 方法描述: 文件上传
	 * 
	 * @param file
	 * @return
	 * @author lixh
	 */

	@RequestMapping("/upload")
	public String upload(@RequestParam("file") MultipartFile file) {
		JSONObject object = new JSONObject();
		if (StringUtils.isEmpty(file)) {
			// 上传文件为空
			object.put("result", 404);
			object.put("msg", "文件为空，请重新上传！");
			return object.toJSONString();
		}
		try {
			FileUpload upload = new FileUpload();
			String filename = file.getOriginalFilename();
			// 本地上传目录
			String filepath = UPLOAD_DIR + "\\" + filename;
			upload.setFilename(filename);
			upload.setFilepath(filepath);
			upload.setId(CommonUtil.getUUID());
			File file2 = new File(UPLOAD_DIR);
			if (!file2.exists()) {
				file2.mkdirs();
			}
			file2 = new File(UPLOAD_DIR, filename);
			boolean isCreateSuccess = file2.createNewFile();
			if (isCreateSuccess) {
				file.transferTo(file2);
			}
			object.put("msg", "文件上传成功！");
			fileservice.AddFile(upload);
		} catch (Exception e) {
			e.printStackTrace();
			object.put("msg", "服务器异常");
			return object.toJSONString();
		}
		return object.toJSONString();
	}

	/**
	 * 
	 * 方法描述: 文件下载
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 * @author lixh
	 */
	@RequestMapping(value = "/download")
	public ResponseEntity<byte[]> download(String id) throws IOException {
		// 获取当前附件信息
		FileUpload fileupload = fileservice.getFileUpload(id);
		// 读取文件
		File file = new File(fileupload.getFilepath());
		// 响应头信息
		HttpHeaders headers = new HttpHeaders();
		// 文件名
		String fileName = new String(fileupload.getFilename().getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
		// 相应文件名
		headers.setContentDispositionFormData("attachment", fileName);
		// 文件类型
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 返回文件
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
	}

	
	/**
	 * 
	 * 方法描述:导出 excel
	 * 
	 * @return
	 * @author lixh
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportexcel")
	public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<>();
		GenerateExcelUtil excelutil = new GenerateExcelUtil();
		List<Map<String, Object>> list = aeollawsserviceimpl.getLawsList(map);
		List<Map<String, Object>> aeollawslist = new ArrayList<Map<String, Object>>();
		if (StringUtils.isEmpty(list)) {
		}
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map3 = new HashMap<String, Object>();
			Map<String, Object> map2 = list.get(i);
			map3.put("lawname", map2.get("LAW_NAME"));
			map3.put("issuetime", map2.get("ISSUE_TIME"));
			map3.put("person", map2.get("INPUT_PERSON"));
			map3.put("lawtype", CommonUtil.LawsType(String.valueOf(map2.get("LAW_TYPE"))));
			map3.put("group", map2.get("LAW_GROUP"));
			map3.put("detail", map2.get("LAW_DETAIL"));
			aeollawslist.add(map3);
		}
		// 建立新的sheet对象（excel的表单）
		XSSFWorkbook workbook = new XSSFWorkbook();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String[] headers = { "法律法规名称", "颁布时间", "录入人", "法律类别", "所属部门", "条款内容" };
		String[] attr = new String[] { "lawname", "issuetime", "person", "lawtype", "group", "detail" };
		ExportExcel<List<Map<String, Object>>> exportExcel = new ExportExcel<List<Map<String, Object>>>();
		return exportExcel.exportXSExcelByColumn(workbook, 0, "法律法规信息", headers, attr, aeollawslist, os, null);

	}

}
